import type { SuggestDataRes, ApiRes, SearchResultRes } from '@/type'
import { http } from '@/utils'
import { makeAutoObservable } from 'mobx'

class SearchStore {
  suggestData: SuggestDataRes
  searchResult: SearchResultRes
  hasMore: boolean
  constructor() {
    makeAutoObservable(this)
    this.suggestData = { options: [] }
    this.searchResult = {
      page: 1,
      per_page: 10,
      results: [],
      total_count: 0,
    }
    this.hasMore = true
  }
  // 获取搜索联想词
  getSuggestData = async (keyword: string) => {
    const res = await http.get<ApiRes<SuggestDataRes>>('/suggestion', {
      params: {
        q: keyword,
      },
    })
    this.suggestData = res.data.data
  }
  // 清除联想
  resetData = () => {
    this.suggestData = { options: [] }
  }
  // 获取搜索结果
  getSearchResult = async (keyword: string) => {
    const res = await http.get<ApiRes<SearchResultRes>>('search', {
      params: {
        page: 1,
        per_page: 10,
        q: keyword,
      },
    })
    // 没有数据 停止监听
    if (res.data.data.results.length === 0) {
      this.hasMore = false
    }
    // 数组拼接
    this.searchResult.results = [
      ...this.searchResult.results,
      ...res.data.data.results,
    ]
  }
  // 清除result
  resetResult = () => {
    this.searchResult = {
      page: 1,
      per_page: 10,
      results: [],
      total_count: 0,
    }
  }
}

export default SearchStore
